package ui;

import javax.swing.*;
import java.awt.*;

/*
 * source code from 《java核心技术 卷1 基础知识》 P323
 */
public class T extends JFrame {

    int DEFAULT_WIDTH = 600;
    int DEFAULT_HEIGHT = 400;

    public T() {
        setTitle("TextComponentFrame");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

        //本frame包含三大板块
        JPanel northPanel = new JPanel();
        JScrollPane scrollPane = null;
        JPanel southPanel = new JPanel();
        add(northPanel, BorderLayout.NORTH);
        add(southPanel, BorderLayout.SOUTH);

        //先来构造northPanel，它包含两个控件
        final TextField textField = new TextField();
        final JPasswordField passwordField = new JPasswordField();

        northPanel.setLayout(new GridLayout(2, 2));
        northPanel.add(new JLabel("UserName:", SwingConstants.RIGHT));//靠右对齐
        northPanel.add(textField);
        northPanel.add(new JLabel("Password:", SwingConstants.RIGHT));//靠右对齐
        northPanel.add(passwordField);

        //再来构造中间板块，它包含一个textArea
        final JTextArea textArea = new JTextArea();
        scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);//添加到窗体

        //构造southPanel，它包含一个button
        southPanel.setLayout(new GridLayout(2, 2));
        JButton insertButton = new JButton("insertButton");
        insertButton.addActionListener(arg0 -> {
            // TODO Auto-generated method stub
            textArea.append("UserName: " + textField.getText() + "\n"
                    + "Password:" + new String(passwordField.getPassword())
                    + "\n");
        });
        southPanel.add(insertButton);
    }

    public static void main(String[] args) {
        //创建窗体并指定标题
        T frame = new T();
        //关闭窗体后退出程序
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //自动适配所有控件大小
        //frame.pack();
        //设置窗体位置在屏幕中央
        frame.setLocationRelativeTo(null);
        //显示窗体
        frame.setVisible(true);
    }
}